

package cn.dinxian.activiti.service.impl;

import cn.dinxian.activiti.domain.WorkflowLeave;
import cn.dinxian.activiti.service.IProcessDefinitionService;
import cn.dinxian.activiti.service.IWorkflowLeaveService;
import cn.dinxian.common.utils.spring.SpringUtils;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import cn.dinxian.common.utils.SecurityUtils;
import cn.dinxian.entity.ActWorkflowFormData;
import cn.dinxian.entity.ActWorkflowFormDataDTO;
import cn.dinxian.entity.ActTaskDTO;
import cn.dinxian.activiti.service.IActTaskService;
import cn.dinxian.activiti.service.IActWorkflowFormDataService;
import cn.dinxian.api.RepositoryService;
import cn.dinxian.api.RuntimeService;
import cn.dinxian.api.TaskService;
import cn.dinxian.common.core.page.PageDomain;
//import org.activiti.api.runtime.shared.query.Pageable;
//import org.activiti.api.task.model.Task;
//import org.activiti.api.task.model.builders.TaskPayloadBuilder;
//import org.activiti.api.task.runtime.TaskRuntime;
//import org.activiti.bpmn.model.FormProperty;
//import org.activiti.bpmn.model.UserTask;
//import org.activiti.engine.RepositoryService;
//import org.activiti.engine.RuntimeService;
//import org.activiti.engine.TaskService;
//import org.activiti.engine.runtime.ProcessInstance;
import cn.dinxian.entity.Base2DTO;
import cn.dinxian.entity.MyProcessInstance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.ParseException;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ActTaskServiceImpl implements IActTaskService {

  @Autowired
  private RepositoryService repositoryService;

 /*   @Autowired
    private TaskRuntime taskRuntime;*/

  @Autowired
  private TaskService taskService;
  @Autowired
  private RuntimeService runtimeService;
  @Autowired
  private IActWorkflowFormDataService actWorkflowFormDataService;
  

  //@Autowired
  //SecurityManager securityManager;


  @Override

  public Page<ActTaskDTO> selectProcessDefinitionList(PageDomain pageDomain) {
    Page<ActTaskDTO> list = new Page<ActTaskDTO>();
    ActTaskDTO actTaskDTO = new ActTaskDTO();
    actTaskDTO.setCurrent(pageDomain.getPageNum());
    
    actTaskDTO.setPageSize(pageDomain.getPageSize());
    actTaskDTO.setUserId( SecurityUtils.getUsername());
    
    
   
     List<String> groupList = SecurityUtils.getGroupList();
    actTaskDTO.setGroupList( groupList);
    //加入权限
     List<ActTaskDTO> tasks = taskService.tasks(actTaskDTO).getData();
    int totalItems = tasks.size();

    list.setTotal(totalItems);
    if (totalItems != 0) {
        //去除重复再转为list
      List<String> processInstanceIdIds = tasks.parallelStream().map(t -> t.getProcessInstanceId())
          .collect(Collectors.toSet()).parallelStream().collect(
              Collectors.toList());
      
       MyProcessInstance myProcessInstanceQueryDTO = new MyProcessInstance();

       List<MyProcessInstance> data = runtimeService.processInstanceQueryList(
          MyProcessInstance.builder().idList(
                  processInstanceIdIds)
              .build()).getData();
     
      List<ActTaskDTO> actTaskDTOS = tasks.stream()
          .map(t -> new ActTaskDTO(t,
              data.parallelStream().filter(pi -> t.getProcessInstanceId().equals(pi.getId()))
                  .findAny().orElse(new MyProcessInstance())))
          .collect(Collectors.toList());
      list.addAll(actTaskDTOS);

    }
    return list;

  }

  @Override
  public List<String> formDataShow(String taskID) {
     List<String> listParam = taskService.getUserTaskForm(
        ActTaskDTO.builder().taskId(taskID).build()).getData().getListParam();
    return listParam;
  }

  @Override
  public Integer formDataSave(String taskID, List<ActWorkflowFormDataDTO> awfs)
      throws ParseException {
    final List<ActWorkflowFormData> actWorkflowFormDataDTOS = repositoryService.formDataSave(
        Base2DTO.builder().taskID(taskID).actWorkflowFormData(awfs).build());
    
    log.info("[MYLOG]:-----ActTaskServiceImpl/formDataSave==>actWorkflowFormDataDTOS:["+ JSONObject.toJSONString(actWorkflowFormDataDTOS)+"]");
    final ActWorkflowFormData actWorkflowFormData = actWorkflowFormDataDTOS.get(0);
    if(actWorkflowFormData.getFormKey().equals("hrVerify")&&actWorkflowFormData.getControlValue().equals("同意")){
      this.updataData("1",actWorkflowFormData.getBusinessKey());
    } else if (actWorkflowFormData.getControlValue().equals("不同意")) {
      this.updataData("2",actWorkflowFormData.getBusinessKey());
    }
    //写入数据库
    return actWorkflowFormDataService.insertActWorkflowFormDatas(actWorkflowFormDataDTOS);
   
  }

  /**
   * 
   * @param msg 审批的结果 1 同意  2 不同意
   * @param businessKey
   */
  public void updataData(String msg,String businessKey){
    WorkflowLeave workflowLeave = new WorkflowLeave();
    workflowLeave.setId(businessKey);
    workflowLeave.setState(msg);

    SpringUtils.getBean(IWorkflowLeaveService.class).updateWorkflowLeave(workflowLeave);
  }
 
}
